import OSS from 'ali-oss'
import axios from './axios'

// let client = new OSS({
//   region: 'oss-cn-chengdu', //地区
//   accessKeyId: 'LTAI4GJV45WFAh1XAj5QAxkB',
//   accessKeySecret: 'KEhNf2Ew8SWrKzkmkeRJS4h41Xx0sv',
//   bucket: 'test-oss-2020'
// })
const filePath = '/Assets/'

function newFileName(length) { // 生成随机文件名
  const data = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
    'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
    'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
    's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
  ]
  let names = ''
  for (let i = 0; i < length; i++) {
    const r = parseInt(Math.random() * 61, 10)
    names += data[r]
  }
  return names
}

let tempCheckpoint
async function OSSmultipartUpload(fileList) {
  const type = fileList[fileList.length - 1].name.split('.')[1]
  const fileName = filePath + newFileName(32) + '.' + type
  const file = fileList[fileList.length - 1].raw
  let fileObj = fileList[fileList.length - 1]
  try {
    const res = await client.multipartUpload(fileName, file, {
      progress: function(p, checkpoint) {
        tempCheckpoint = checkpoint
      }
    })
    if (res.res.status === 200) {
      fileObj = {
        ...fileObj,
        res
      }
      return fileObj
    } else {
      return '上传失败'
    }
  } catch (e) {
    // console.log(e);
  }
}

// 暂停
function OSSpause() {
  client.cancel()
}

// OSS上传
var num = 0
async function OSSUploadImage(fileList, isPublic = false) {
  let sts
  if (isPublic) {
    sts = await axios.get('/system/sts/build?bucketType=1')
  } else {
    // 上传图片
    sts = await axios.get('/system/sts/build')
  }
  sts = sts.data
  console.log(sts, 4566)
  return new Promise((resolve, reject) => {
    const client = new OSS({
      endpoint: `${sts.endpoint}`,
      accessKeyId: sts.credentials.accessKeyId,
      accessKeySecret: sts.credentials.accessKeySecret,
      stsToken: sts.credentials.securityToken,
      bucket: sts.bucket
    })
    const type = fileList[num].name.split('.')[1]
    const fileName = '/' + sts.prefix + '/' + newFileName(32) + '.' + type
    const file = fileList[num].raw
    let fileObj = fileList[num]
    num++
    setTimeout(() => {
      num = 0
    }, 1000)

    // console.log(sts.endpoint,44555);
    client.put(fileName, file).then(res => {
      if (res.res.status === 200) {
        fileObj = {
          ...fileObj,
          res
        }
        resolve(fileObj)
      } else {
        reject('上传失败')
      }
    })
    //   client.put(fileName, file).then(res => {
    //     if (res.res.status === 200) {
    //       fileObj = {
    //         ...fileObj,
    //         res
    //       }
    //       resolve(fileObj)
    //     } else {
    //       reject('上传失败')
    //     }
    //   }).catch(err => {
    //     reject(err)
    //   })
  })
}
// async function OSSUploadImage(fileList,sts) { // 上传图片
//   let type = fileList[fileList.length - 1].name.split('.')[1]
//   let fileName = filePath + newFileName(32) + '.' + type
//   let file = fileList[fileList.length - 1].raw
//   let fileObj = fileList[fileList.length - 1]
//   try {
//     let res = await client.put(fileName, file)
//     if (res.res.status === 200) {
//       fileObj = {
//         ...fileObj,
//         res
//       }
//       return fileObj
//     } else {
//       return '上传失败'
//     }

//   } catch (e) {
//     console.log(e);
//   }
// }

// OSS下载
async function OSSDownload(name, path) {
  let sts = await axios.get('/system/sts/build')
  sts = sts.data

  const client = new OSS({
    // region: 'oss-cn-chengdu', //地区
    endpoint: `${sts.endpoint}`,
    accessKeyId: sts.credentials.accessKeyId,
    accessKeySecret: sts.credentials.accessKeySecret,
    stsToken: sts.credentials.securityToken,
    bucket: sts.bucket
  })
  let newPath = path
  if (path.includes('.com')) {
    newPath = path.split('aliyuncs.com/')[1]
  }
  const response = {
    'content-disposition': `attachment; filename=${encodeURIComponent(name)}`
  }
  const res = client.signatureUrl(newPath, { response })
  window.open(res)
}

async function OSSUploadImageOne(oneFile, isPublic = false) {
  let sts
  if (isPublic) {
    sts = await axios.get('/system/sts/build?bucketType=1')
  } else {
    // 上传图片
    sts = await axios.get('/system/sts/build')
  }
  sts = sts.data
  return new Promise((resolve, reject) => {
    const client = new OSS({
      endpoint: `${sts.endpoint}`,
      accessKeyId: sts.credentials.accessKeyId,
      accessKeySecret: sts.credentials.accessKeySecret,
      stsToken: sts.credentials.securityToken,
      bucket: sts.bucket
    })
    const type = oneFile.name.split('.')[1]
    const fileName = '/' + sts.prefix + '/' + newFileName(32) + '.' + type
    const file = oneFile.raw
    let fileObj = oneFile
    client.put(fileName, file).then(res => {
      if (res.res.status === 200) {
        fileObj = {
          ...fileObj,
          res
        }
        resolve(fileObj)
      } else {
        reject('上传失败')
      }
    })
  })
}

export default {
  OSSUploadImage,
  OSSUploadImageOne,
  OSSDownload,
  OSSmultipartUpload,
  OSSpause
}
